#!/bin/bash

# 获取当前目录的绝对路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_PATH="${SCRIPT_DIR}/configs/config.json"

# 检查Python路径
if command -v python3 &> /dev/null; then
    PYTHON_PATH=$(which python3)
elif command -v python &> /dev/null; then
    PYTHON_PATH=$(which python)
else
    echo "错误: 未找到Python。请确保已安装Python。"
    exit 1
fi

# 检查配置文件是否存在
if [ ! -f "${CONFIG_PATH}" ]; then
    echo "警告: 配置文件 ${CONFIG_PATH} 不存在。"
    read -p "请输入配置文件路径: " CONFIG_PATH
    if [ ! -f "${CONFIG_PATH}" ]; then
        echo "错误: 配置文件 ${CONFIG_PATH} 不存在。"
        exit 1
    fi
fi

# 创建服务文件
cat > /tmp/media_service.service << EOF
[Unit]
Description=Media Info Processing Service
After=network.target

[Service]
User=$(whoami)
WorkingDirectory=${SCRIPT_DIR}
ExecStart=${PYTHON_PATH} ${SCRIPT_DIR}/flask_server.py --config=${CONFIG_PATH}
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# 复制服务文件到systemd目录
echo "正在安装服务文件..."
sudo cp /tmp/media_service.service /etc/systemd/system/

# 重新加载systemd配置
echo "重新加载systemd配置..."
sudo systemctl daemon-reload

# 启用服务
echo "启用服务..."
sudo systemctl enable media_service.service

echo "====================================================="
echo "服务安装完成！"
echo "====================================================="
echo "服务名称: media_service"
echo "配置文件: ${CONFIG_PATH}"
echo "工作目录: ${SCRIPT_DIR}"
echo "Python路径: ${PYTHON_PATH}"
echo "====================================================="
echo "管理命令:"
echo "启动服务: sudo systemctl start media_service"
echo "停止服务: sudo systemctl stop media_service"
echo "重启服务: sudo systemctl restart media_service"
echo "查看状态: sudo systemctl status media_service"
echo "查看日志: sudo journalctl -u media_service"
echo "查看实时日志: sudo journalctl -u media_service -f"
echo "====================================================="

# 询问是否立即启动服务
read -p "是否立即启动服务? (y/n): " START_NOW
if [ "$START_NOW" = "y" ] || [ "$START_NOW" = "Y" ]; then
    echo "正在启动服务..."
    sudo systemctl start media_service
    echo "服务已启动。查看状态:"
    sudo systemctl status media_service
fi